import subprocess
import yaml
from flask import Flask, request, jsonify
import logging
from waitress import serve

# 创建一个新的日志记录器
new_logger = logging.getLogger('new_logger')
new_logger.setLevel(logging.DEBUG)

# 创建一个handler，用于在控制台上打印日志
ch = logging.StreamHandler()

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)

# 给logger添加handler
new_logger.addHandler(ch)
# 阻止日志消息被传递给更高级别的日志记录器
new_logger.propagate = False
app = Flask(__name__)

TOKEN = "QP77ZUFXNO0PO9AWVPSYLS5WCXUSCA1NCL2BSLV8"


@app.route("/update_container", methods=["POST"])
def update_container():
    data = request.get_json()
    new_logger.info(f"Received request: {data}")
    if data.get("token") == TOKEN:
        volumes = data.get("volumes", {})
        container_name = data.get("containerName")
        network_mode = data.get("networkMode")
        image = data.get("image")
        env = data.get("env", {})
        ports = data.get("ports", {})
        restart = data.get("restart", "no")
        privileged = data.get("privileged", False)
        args = ["docker", "run", "-d", "--name", container_name]
        if network_mode:
            args.extend(["--network", network_mode])
        if restart:
            args.extend(["--restart", restart])
        if privileged:
            args.append("--privileged")
        for k, v in env.items():
            args.extend(["-e", f"{k}={v}"])
        for k, v in volumes.items():
            args.extend(["-v", f"{k}:{v}"])
        for k, v in ports.items():
            args.extend(["-p", f"{v}:{k}"])
        args.append(image)
        output = subprocess.check_output(["docker", "ps", "-a", "--format", "{{.Names}}"])
        output = output.decode("utf-8")
        if container_name in output:
            subprocess.call(["docker", "rm", "-f", container_name])
        output = subprocess.check_output(args)
        output = output.decode("utf-8")
        container_id = output.strip()
        compose = {
            "version": "3",
            "services": {
                container_name: {
                    "image": image,
                    "container_name": container_name
                }
            }
        }
        if network_mode:
            compose["services"][container_name]["network_mode"] = network_mode
        if restart:
            compose["services"][container_name]["restart"] = restart
        if env:
            compose["services"][container_name]["environment"] = env
        if volumes:
            compose["services"][container_name]["volumes"] = [f"{k}:{v}" for k, v in volumes.items()]
        if ports:
            compose["services"][container_name]["ports"] = [f"{v}:{k}" for k, v in ports.items()]
        if privileged:
            compose["services"][container_name]["privileged"] = True
        compose = yaml.dump(compose, indent=4)
        compose_path = f"./{container_name}.yml"
        with open(compose_path, "w") as f:
            f.write(compose)
        return jsonify({"message": "Container created successfully", "container_id": container_id,
                        "docker_compose_path": compose_path})
    else:
        return jsonify({"message": "Token错误!"})


if __name__ == '__main__':
    new_logger.info("Dockerze 应用已正常启动!")
    serve(app, host='0.0.0.0', port=5000)
